<template>
  <!-- 顶部tab切换按钮 -->
  <div class="tab-switch-bar flex justify-center items-center gap-8 mt-12 mb-6">
    <!-- :class="['tab-switch-btn', activeTab === 'expert' ? 'active' : '']" -->

    <!-- <button
          :class="['tab-switch-btn', activeTab === 'expert' ? 'active' : '']"
          @click="handleActiveTabChange('expert')"
        >
          <span class="tab-icon">👨‍🎓</span>
          <span>专家频道</span>
        </button>
        <button
          :class="['tab-switch-btn', activeTab === 'qa' ? 'active' : '']"
          @click="handleActiveTabChange('qa')"
        >
          <span class="tab-icon">💬</span>
          <span>问答频道</span>
        </button> -->
  </div>
  <div class="expert-page flex gap-8 justify-center min-h-screen pb-16 max-w-[1600px] mx-auto"
    v-if="activeTab === 'expert'">
    <div class="question-page-root">
      <div class="main-layout">
        <div class="main-left ml-6">
          <el-card class="main-card" shadow="hover">
            <!-- <QuestionTabs :tabs="tabs" :activeTab="activeTabInnner" @update:activeTab="onTabChange" /> -->
            <LfTabs :activeIndex="activeIndex" ref="lfTabsRef" :tabOptions="tabs" :onTopicClick="onTabChange" />
            <!-- 顶部标题区 -->
            <!-- <div class="pt-12 pb-6 text-center">
        <h1 class="text-3xl font-extrabold text-blue-800 tracking-tight mb-2">专家频道</h1>
        <div class="text-base text-slate-500">飞行安全 · 专业解答 · 智能推荐</div>
      </div> -->
            <!-- 专家列表区（含筛选区和卡片区） -->
            <div class="expert-list-area">

              <!-- 筛选区 -->
              <div
                class="filter-bar-container flex items-center gap-4 px-8 pt-5 rounded-2xl shadow-lg border border-[#e6eaf2] glass-blur whitespace-nowrap overflow-x-auto">
                <div class="flex-1 min-w-0">
                  <ExpertFilterBar v-model:search="search" v-model:field="selectedField" v-model:sort="sortType"
                    :fields="allFields" :sort-options="sortOptions" class="rounded-2xl filter-bar-beauty"
                    @reset="handleFilterReset" @change="handleFilterChange" />
                </div>
                <!-- <el-button
            v-if="isAdmin"
            type="primary"
            class="add-btn ml-8 shrink-0"
            @click="openDialog()"
          >
            <i class="el-icon-plus mr-1"></i> 新增专家
          </el-button> -->
              </div>
              <!-- 标签筛选提示 -->
              <!-- <div v-if="activeTag" class="mb-4 text-sm text-blue-600 flex items-center gap-2">
          <span>已筛选标签：</span>
          <el-tag type="success" effect="dark" class="cursor-pointer" @click="clearTag">{{ activeTag }} <i class="el-icon-close"></i></el-tag>
          <el-button size="small" link type="primary" @click="clearTag">清除筛选</el-button>
        </div> -->
              <!-- 分割线 -->
              <div class="h-px bg-gradient-to-r from-blue-100 to-transparent my-6"></div>
              <!-- 加载骨架屏 -->
              <div v-if="isLoading">
                <ExpertSkeleton :count="20" card-per-row="3" />
              </div>
              <!-- 专家卡片区 v-else-->
              <div v-else>
                <div class="recommend-title flex items-center gap-2 mb-4">
                  <span class="font-bold text-xl text-blue-800">专家</span>
                  <div class="h-2 w-2 rounded-full bg-gradient-to-r from-blue-400 to-blue-600"></div>
                  <div class="flex-1 h-px bg-gradient-to-r from-blue-200 to-transparent"></div>
                </div>
                <div class="grid gap-8 md:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5">
                  <ExpertCard v-for="expert in pagedExperts" :key="expert.id" :expert="expert" :tag-color="tagColor"
                    @select-tag="selectTag" @edit="editExpert" @click="goToDetail(expert)" />
                </div>
              </div>

              <!-- 空状态 -->
              <div v-if="!isLoading && pagedExperts.length === 0"
                class="flex flex-col items-center justify-center py-16 text-slate-400">
                <img src="@/assets/empty-expert.svg" class="w-32 mb-4" />
                <div>暂无符合条件的专家，试试更换筛选条件</div>
              </div>
              <!-- 分割线 -->
              <div class="h-px bg-gradient-to-r from-blue-100 to-transparent my-10"></div>
              <!-- 分页 -->
              <div class="flex justify-center mt-4">
                <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
                  v-model:current-page="currentPage" hide-on-single-page class="custom-pagination" />
              </div>

              <!-- <div class="recommend-title flex items-center gap-2 mb-4">
          <span class="font-bold text-xl text-blue-800">统计</span>
          <div class="h-2 w-2 rounded-full bg-gradient-to-r from-blue-400 to-blue-600"></div>
          <div class="flex-1 h-px bg-gradient-to-r from-blue-200 to-transparent"></div>
        </div>
        <div>
          <ExpertStatistics />
        </div> -->
            </div>
          </el-card>
        </div>
      </div>
    </div>
    <!-- 标签云 -->
    <ExpertTagCloud :tags="tagStats" :active-tag="activeTag" :tag-color="tagColor" @select="selectTag"
      class="w-[280px] flex-shrink-0 expertTagCloud" />

  </div>
  <Question :refresh-data="refreshData" @getActiveTab="getActiveTab" v-if="activeTab === 'qa'" />
   <QuestionDialog v-model:visible="showQuestionDialog" @success="handleQuestionSuccess" />

</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useExpertListQuery } from '@/composables/useExpertDataQuery'
import { getSpecialtyTag, getSpecialtyTagTree } from '@/axios/api/expert'
import ExpertCard from './components/ExpertCard.vue'
import ExpertTagCloud from './components/ExpertTagCloud.vue'
import ExpertFilterBar from './components/ExpertFilterBar.vue'
import ExpertSkeleton from './components/ExpertSkeleton.vue'
import 'vue3-virtual-scroller/dist/vue3-virtual-scroller.css'
import { getQuestionHotTag } from '@/axios/api/question'
import ExpertStatistics from './components/ExpertStatistics.vue'
import avatar from '@/assets/avatar.png'
import Question from '@/views/Question/Question.vue'
import { getUserInfo } from '@/utils/webStorage'
import LfTabs from '@/components/commonUI/LfTabs.vue'
import QuestionDialog from '@/views/Submit/components/QuestionDialog.vue'


import { useGlobalStore } from '@/stores/globalStore'
const globalStore = useGlobalStore()

const showQuestionDialog = ref(false)
const refreshData = ref(false)



// 事件处理函数
const handleQuestionSuccess = () => {
  showQuestionDialog.value = false
  refreshData.value = !refreshData.value
}


//头部按钮点击
watch(
  () => globalStore.isShowQuestionDialog,
  (val) => {
    if (val) {
      showQuestionDialog.value = true
    }
  }
)


const activeIndex = ref(0)
const activeTabInnner = ref('')
let tabs = []
const curInfo = getUserInfo()
if (JSON.stringify(curInfo) == '{}') {
  tabs = [
    { name: '最新问题', id: 'create_time' },
    { name: '人气问题', id: 'heat_score' },
    { name: '经典答疑', id: 'answer' },
    { name: '专家', id: 'expert' },
  ]
  activeTabInnner.value = 'create_time'
} else if (curInfo.type == 1) {
  tabs = [
    { name: '为您推荐', id: 'recommend' },
    { name: '请您回答', id: 'invite' },
    { name: '最新问题', id: 'create_time' },
    { name: '人气问题', id: 'heat_score' },
    { name: '经典答疑', id: 'answer' },
    { name: '我的提问', id: 'my' },
    { name: '专家', id: 'expert' },
  ]
  activeTabInnner.value = 'recommend'

} else if (curInfo.type == 0) {
  tabs = [
    { name: '为您推荐', id: 'recommend' },
    { name: '最新问题', id: 'create_time' },
    { name: '人气问题', id: 'heat_score' },
    { name: '经典答疑', id: 'answer' },
    { name: '我的提问', id: 'my' },
    { name: '专家', id: 'expert' },
  ]
  activeTabInnner.value = 'recommend'

}

const router = useRouter()
const defaultAvatar = avatar

// 专业领域标签列表
const specialtyTags = ref([])

// 获取专业领域标签树
const fetchSpecialtyTags = async () => {
  try {
    const res = await getSpecialtyTagTree()
    if (res.code === 0 && res.data) {
      specialtyTags.value = res.data
    }
  } catch (error) {
    console.error('获取专业领域标签树失败:', error)
  }
}

const search = ref('')
const selectedField = ref('')
const sortType = ref('')
const currentPage = ref(1)
const pageSize = 10
const activeTag = ref('')
const activeTab = ref('expert')

// 请求参数
const queryParams = computed(() => ({
  status: '', // 默认状态为1
  keyword: search.value,
  activeSort: '',
  specialtyTagIds: Array.isArray(selectedField.value) ? selectedField.value.join(',') : selectedField.value,
  limit: pageSize,
  page: currentPage.value,
}))

// 使用 vue-query 获取专家列表
const { data: expertData, isLoading, refetch } = useExpertListQuery(queryParams)

// 监听分页变化
watch(
  currentPage,
  () => {
    refetch()
  },
  { flush: 'post' },
)




// 从响应中获取专家列表和总数
const experts = computed(() => {
  const records = expertData.value?.data?.list || []
  return records.map((expert) => ({
    ...expert,
    id: expert.id,
    name: expert.name,
    field: typeof expert.specialtyTagNames === 'string' ? expert.specialtyTagNames : expert.specialtyTagNames || '', // 专业领域
    fieldIds: typeof expert.specialtyTagNames === 'string' ? expert.specialtyTagNames : expert.specialtyTagNames || '', // 专业领域
    org: expert.orgName || '', // 单位
    title: expert.honor || '', // 职称/荣誉
    intro: expert.introduction || '', // 简介
    contact: expert.contact || '', // 联系方式
    email: expert.email || '', // 邮箱
    avatar: expert.avatar || defaultAvatar, // 头像
    createTime: expert.createTime, // 创建时间
    updateTime: expert.updateTime, // 更新时间
  }))
})

const total = computed(() => expertData.value?.data?.totalCount || 0)

const tagColorMap = ['success', 'info', 'warning', 'danger', 'primary']
function tagColor(tag) {
  let hash = 0
  for (let i = 0; i < tag.length; i++) hash += tag.charCodeAt(i)
  return tagColorMap[hash % tagColorMap.length]
}

const allFields = computed(() => specialtyTags.value)
const sortOptions = [
  { label: '推荐排序', value: 'recommend' },
  { label: '答复数最多', value: 'reply' },
  { label: '最佳答案率最高', value: 'bestRate' },
  { label: '最新入驻', value: 'newest' },
]

// 由于使用了后端分页，不再需要前端过滤
const filteredExperts = computed(() => experts.value)
console.log(filteredExperts.value)

// 由于使用了后端分页，直接使用接口返回的数据
const pagedExperts = computed(() => filteredExperts.value)

const tagStats = ref([])

// 获取热门标签数据
const fetchHotTags = async () => {
  try {
    const res = await getQuestionHotTag()
    if (res.code === 0 && res.data) {
      // 将接口返回的数据结构转换为组件需要的格式
      tagStats.value = res.data.map((tag) => ({
        name: tag.tagName, // 标签名称
        count: tag.questionCount, // 问题数量
        id: tag.tagId, // 添加标签ID
      }))
    }
  } catch (error) {
    console.error('获取热门标签失败:', error)
  }
}

// 在组件挂载时获取热门标签
onMounted(() => {
  activeTab.value = "qa"
  fetchSpecialtyTags()
  fetchHotTags() // 添加获取热门标签的调用
  const questionTab = sessionStorage.getItem('questionTab')
  if (questionTab) {
    tabs.forEach((item, index) => {
      if (item.id == questionTab) {
        activeIndex.value = index
      }
    })
  }
})
function onTabChange(index, id, name, scrollLeft) {
  activeTabInnner.value = id
  activeIndex.value = index
  if (id !== 'expert') {
    activeTab.value = "qa"
    sessionStorage.setItem('questionTab', id)
  }
}

function getActiveTab(active) {
  if (active.value === 'expert') {
    activeTab.value = active.value
    activeTabInnner.value = active.value
    tabs.forEach((item, index) => {
      if (item.id == active.value) {
        activeIndex.value = index
      }
    })
  }
}

function selectTag(tagInfo) {
  console.log(tagInfo)
  if (activeTag.value === tagInfo.name) {
    activeTag.value = ''
    selectedField.value = '' // 清空专业领域ID
  } else {
    activeTag.value = tagInfo.name
    selectedField.value = tagInfo.id // 设置专业领域ID
    currentPage.value = 1
  }
  refetch() // 添加重新请求数据
}
function clearTag() {
  activeTag.value = ''
  selectedField.value = '' // 清空专业领域ID
  currentPage.value = 1 // 重置页码
  refetch() // 添加重新请求数据
}
function goToDetail(expert) {
  router.push(`/expert/${expert.id}`)
}

// 权限控制：只有 isAdmin 为 true 时显示新增专家按钮

// 处理筛选条件变化
const handleFilterChange = () => {
  currentPage.value = 1 // 重置页码
  refetch() // 重新请求数据
}

// 处理筛选条件重置
const handleFilterReset = () => {
  // 重置页码
  currentPage.value = 1
  // 重置标签筛选
  activeTag.value = ''
  // 重新获取数据
  refetch()
}

</script>

<style scoped>
.expertTagCloud {
  margin-top: 20px;
}

.question-page-root {
  min-height: 100vh;
  /* background: #f6f8fa; */
  padding: 20px 0 32px 0;
}

.main-card {
  flex: 1 1 0;
  min-width: 0;
  /* max-width: 850px; */
  border-radius: 20px;
  box-shadow: 0 4px 32px 0 rgba(64, 158, 255, 0.06);
  background: #fff;
  padding: 0;
  border: none;
  display: flex;
  flex-direction: column;
}

.el-tag {
  margin-bottom: 4px;
}

.expert-card {
  box-shadow: 0 2px 12px 0 rgba(56, 112, 255, 0.06);
  border: 1.5px solid #e6eaf2;
  transition: box-shadow 0.2s, border 0.2s;
}

.expert-card:hover {
  box-shadow: 0 6px 24px 0 rgba(56, 112, 255, 0.13);
  border-color: #a3c8fa;
}

.avatar-ring {
  border-radius: 50%;
  padding: 4px;
  background: linear-gradient(135deg, #a3c8fa 0%, #e6f0fa 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.custom-pagination :deep(.el-pager li) {
  border-radius: 1.5rem;
  margin: 0 4px;
  font-size: 18px;
  min-width: 40px;
  height: 40px;
  line-height: 40px;
  color: #1765ad;
  transition: background 0.2s, color 0.2s;
}

.custom-pagination :deep(.el-pager li.active) {
  background: linear-gradient(90deg, #4f9cff 0%, #1765ad 100%);
  color: #fff;
  font-weight: bold;
  box-shadow: 0 2px 8px 0 rgba(56, 112, 255, 0.1);
}

.custom-pagination :deep(.el-pager li):hover {
  background: #e6f0fa;
  color: #1765ad;
}

.filter-bar-container {
  /* 保证筛选区单行排列，内容溢出时横向滚动 */
  flex-wrap: nowrap !important;
  white-space: nowrap;
  overflow-x: auto;
  background: linear-gradient(120deg, rgba(250, 253, 255, 0.85) 0%, rgba(242, 246, 252, 0.95) 100%);
  backdrop-filter: blur(18px);
  border-radius: 2.5rem;
  border: 2.5px solid #e6eaf2;
  box-shadow: 0 8px 32px 0 rgba(56, 112, 255, 0.13);
  /* margin-bottom: 2rem; */
  /* padding: 2.2rem 2.5rem; */
  align-items: center;
  transition: box-shadow 0.2s, background 0.2s, border 0.2s;
  position: relative;
  gap: 1.5rem;
}

.filter-bar-beauty :deep(.el-input),
.filter-bar-beauty :deep(.el-select) {
  border-radius: 2rem !important;
  margin-right: 22px;
  min-width: 150px;
  font-size: 16px;
  background: #fafdff !important;
  transition: border 0.2s, box-shadow 0.2s, background 0.2s;
}

.filter-bar-beauty :deep(.el-input__wrapper),
.filter-bar-beauty :deep(.el-select .el-input__wrapper) {
  border-radius: 2rem !important;
  box-shadow: none;
  border: 1.5px solid #e6eaf2;
  background: #fff !important;
  transition: border 0.2s, box-shadow 0.2s, background 0.2s;
}

.filter-bar-beauty :deep(.el-input__wrapper:hover),
.filter-bar-beauty :deep(.el-select .el-input__wrapper:hover),
.filter-bar-beauty :deep(.el-input__wrapper.is-focus),
.filter-bar-beauty :deep(.el-select .el-input__wrapper.is-focus) {
  border-color: #4f9cff;
  box-shadow: 0 0 0 2px #e6f0fa;
  background: #f0f7ff !important;
}

.filter-bar-beauty :deep(.el-input__inner),
.filter-bar-beauty :deep(.el-select__selected-item) {
  color: #1765ad;
}

.add-btn {
  background: linear-gradient(90deg, #4f9cff 0%, #1765ad 100%);
  color: #fff;
  border-radius: 2rem;
  font-weight: bold;
  font-size: 16px;
  padding: 0 2rem;
  box-shadow: 0 2px 8px 0 rgba(56, 112, 255, 0.13);
  border: none;
  transition: background 0.2s, color 0.2s;
  display: flex;
  align-items: center;
  height: 48px;
  letter-spacing: 1px;
}

.add-btn:hover {
  background: linear-gradient(90deg, #1765ad 0%, #4f9cff 100%);
  color: #fff;
}

@media (max-width: 900px) {
  .filter-bar-container {
    flex-direction: column;
    gap: 1.5rem;
    padding: 1.5rem 1rem;
    flex-wrap: wrap !important;
    white-space: normal;
    overflow-x: visible;
  }

  .add-btn {
    width: 100%;
    justify-content: center;
    margin-top: 1rem;
  }
}

.glass-blur {
  background: linear-gradient(90deg, #fafdffcc 0%, #f2f6fccf 100%) !important;
  backdrop-filter: blur(12px);
  border: 1.5px solid #e6eaf2;
  box-shadow: 0 8px 32px 0 rgba(56, 112, 255, 0.1);
}

.expert-list-area {
  background: linear-gradient(135deg, #fafdff 0%, #f2f6fc 100%);
  border-radius: 2.5rem;
  box-shadow: 0 4px 24px rgba(56, 112, 255, 0.08);
  margin-bottom: 2rem;
  padding: 0.5rem 2rem;
  margin-left: 2rem;
}

.tab-switch-bar {
  margin-top: 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
  gap: 0;
  /* 按钮之间用分割线分隔 */
}

.tab-switch-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 700;
  color: #1765ad;
  background: linear-gradient(90deg, #fafdff 0%, #e3f0ff 100%);
  border: 2.5px solid #4f9cff;
  border-radius: 2.5rem;
  padding: 12px 48px;
  box-shadow: 0 4px 16px rgba(56, 112, 255, 0.1);
  transition: background 0.25s, color 0.25s, border 0.25s, box-shadow 0.25s, transform 0.18s;
  letter-spacing: 1px;
  cursor: pointer;
  margin: 0 0.5rem;
  position: relative;
  z-index: 1;
  outline: none;
  overflow: hidden;
}

.tab-switch-btn .tab-icon {
  font-size: 22px;
  margin-right: 6px;
}

.tab-switch-btn.active {
  background: linear-gradient(90deg, #4f9cff 0%, #1765ad 100%);
  color: #fff;
  border-color: #1765ad;
  box-shadow: 0 6px 24px rgba(56, 112, 255, 0.18);
  transform: translateY(-2px) scale(1.04);
}

.tab-switch-btn:not(.active):hover {
  background: #e3f0ff;
  color: #1765ad;
  border-color: #1765ad;
  box-shadow: 0 2px 12px rgba(56, 112, 255, 0.13);
  transform: translateY(-1px) scale(1.02);
}

@media (max-width: 900px) {
  .tab-switch-bar {
    gap: 0;
    flex-direction: row;
    padding: 0 8px;
  }

  .tab-switch-btn {
    padding: 10px 18px;
    font-size: 15px;
    margin: 0 4px;
    min-width: 110px;
    justify-content: center;
  }

  .tab-switch-btn .tab-icon {
    font-size: 18px;
    margin-right: 4px;
  }
}
</style>
